<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.userName"
        clearable
        :placeholder="$t('table.user.userName')"
        style="width: 200px;"
        class="filter-item"
      />
      <el-select
        v-model="listQuery.status"
        class="filter-item"
        :placeholder="$t('table.status')"
        clearable
      >
        <el-option
          v-for="item in userStatus"
          :key="item.key"
          :label="$t(item.display_name)"
          :value="item.key"
        />
      </el-select>
      <SelectTree
        :props="props"
        :options="deptList"
        @getValue="getValue($event)"
        :placeholderSelect="$t('table.dept.select')"
        :placeholder="$t('table.dept.search')"
      />
      <searchBtn @handle="handleFilter" />
      <addBtn auth="sys:user:add" @handle="handleBtn([1])" />
    </div>
    <el-table
      v-loading="listLoading"
      :data="dataList"
      row-key="userId"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :max-height="tableHeight"
    >
      <el-table-column
        :label="$t('table.id')"
        align="center"
        type="index"
        style="width:50px;"
        min-width="12%"
      >
        <template slot-scope="{row}">{{ row.userId }}</template>
      </el-table-column>
      <el-table-column
        :label="$t('table.user.userName')"
        min-width="15%"
        align="center"
        prop="userName"
      >
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.user.name')" min-width="15%" align="center" prop="name">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.user.deptName')"
        min-width="15%"
        align="center"
        prop="deptId"
      >
        <template slot-scope="{row}">
          <span>{{ getDetpName(row.deptId) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.status')" min-width="15%" align="center" prop="status">
        <template slot-scope="{row}">
          <span v-if="row.status==='0'" style="color:red;">{{ $t('table.status1') }}</span>
          <span v-else style="color:blue;">{{ $t('table.status2') }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('table.actions')"
        align="center"
        min-width="25%"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <groupBtn :auths="btnGroup" :param="row" @handle="handleBtn(arguments)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :title="$t(textMap[dialogStatus])" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item :label="$t('table.user.userName')" prop="userName">
          <el-input v-model="temp.userId" style="display:none;" />
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item :label="$t('table.user.name')" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>

        <el-form-item :label="$t('table.user.deptName')" prop="deptId">
          <SelectTree
            :props="props"
            :value="temp.deptId"
            :options="deptList"
            @getValue="getDeptId($event)"
          />
        </el-form-item>
        <el-form-item :label="$t('table.status')" prop="status">
          <el-select v-model="temp.status" class="filter-item">
            <el-option
              v-for="item in userStatus"
              :key="item.key"
              :label="$t(item.display_name)"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="createData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchUserList,
  updateUser,
  findByUserId,
  deleteByUserId,
  fetchDeptList
} from '@/api/system'
import groupBtn from '@/components/buttonGroup/groupBtn'
import searchBtn from '@/components/buttonGroup/searchBtn'
import addBtn from '@/components/buttonGroup/addBtn'
import Pagination from '@/components/Pagination'
import SelectTree from '@/components/SelectTree/selectTree'
const userStatus = [
  { key: '0', display_name: 'table.status1' },
  { key: '1', display_name: 'table.status2' }
]
export default {
  name: 'User',
  components: { groupBtn, searchBtn, addBtn, Pagination, SelectTree },
  data() {
    return {
      tableHeight: window.innerHeight - 285,
      btnGroup: [
        {
          id: 2,
          auth: 'sys:user:edit',
          btnType: 'success',
          name: 'table.edit'
        },
        {
          id: 3,
          auth: 'sys:user:delete',
          btnType: 'danger',
          name: 'table.delete'
        }
      ],
      dataList: [],
      deptList: [],
      props: {
        // 配置项（必选）
        value: 'deptId',
        label: 'name',
        children: 'children'
      },
      treeValue: 0,
      total: 0,
      userStatus,
      listLoading: true,
      listQuery: {
        userName: undefined,
        page: 1,
        limit: 20
      },
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'table.user.edit',
        create: 'table.user.create'
      },
      rules: {
        userName: [
          {
            required: true,
            message: this.$t('table.user.nameRule'),
            trigger: 'blur'
          }
        ]
      },
      downloadLoading: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.loadDepts()
    this.getList()
  },
  methods: {
    loadDepts() {
      fetchDeptList({}).then(response => {
        const depts = response.content
        this.deptList = depts
      })
    },
    getValue(deptId) {
      this.listQuery.deptId = deptId
    },
    getDeptId(deptId) {
      this.temp.deptId = deptId
    },
    getDetpName(deptId) {
      const depts = this.deptList.filter(item => item.deptId === deptId)
      if (depts.length > 0) {
        return depts[0]['name']
      }
    },
    handleFilter() {
      this.getList()
    },
    getList() {
      this.listLoading = true
      fetchUserList(this.listQuery).then(response => {
        this.dataList = response.content.records
        this.total = response.content.total
        setTimeout(() => {
          this.listLoading = false
        }, 1000)
      })
    },
    resetTemp() {
      this.temp = {
        userId: undefined,
        userName: '',
        deptId: 0,
        status: '0'
      }
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateUser(this.temp).then(data => {
            if (this.temp.userId) {
              this.dataList.forEach(item => {
                if (item.userId === this.temp.userId) {
                  item.userName = this.temp.userName
                  item.status = this.temp.status
                  item.deptId = this.temp.deptId
                  item.name = this.temp.name
                }
              })
            } else {
              this.temp.userId = data.content.userId
              this.dataList.push(this.temp)
            }
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: data.msg
            })
          })
        }
      })
    },
    /** 按钮回调 **/
    handleBtn: function(param) {
      const id = param[0]
      const row = param[1]
      this.resetTemp()
      console.log(this.temp)
      if (id === 1) {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (id === 2) {
        findByUserId(row.userId).then(data => {
          const content = data.content
          this.temp = JSON.parse(JSON.stringify(content))
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        })
      } else if (id === 3) {
        this.$confirm('此操作将删除角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            deleteByUserId(row.userId).then(data => {
              this.dataList.splice(
                this.dataList.findIndex(item => item.userId === row.userId),
                1
              )
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    }
  }
}
</script>
